package com.bw.documents.manager

import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.bw.common.mvi.BaseActivity
import com.bw.documents.R
import com.bw.documents.manager.adapter.DocumentsAdapter
import com.bw.documents.databinding.ActivityDocumentsBinding
import com.bw.documents.local.entity.LocalDocumentsType
import com.bw.widget.decoration.SignLineDecoration
import com.bw.widget.header.MDMRefreshHeader
import com.scwang.smart.refresh.footer.ClassicsFooter
import kotlinx.coroutines.launch
import java.io.File

@Route(path = "/documents/DocumentsActivity")
class DocumentsActivity : BaseActivity<ActivityDocumentsBinding, DocumentsViewModel>() {

    private val filePath : String by lazy { getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)!!.absolutePath }

    private val documentsAdapter : DocumentsAdapter by lazy {
        DocumentsAdapter()
    }

    override fun createVM(): DocumentsViewModel {
        return viewModels<DocumentsViewModel>().value
    }

    override fun initView() {
        v.documentsPageBar.backImg.setOnClickListener { finish() }
        v.documentsPageBar.titleTv.text = "文件"
        v.documentsSmart.setRefreshHeader(MDMRefreshHeader(this,null))
        v.documentsSmart.setRefreshFooter(ClassicsFooter(this))
        v.documentsSmart.setOnRefreshListener { vm.selDocuments(1) }
        v.documentsSmart.setOnLoadMoreListener { vm.loadDocuments(1) }
        v.documentsUploadImg.setOnClickListener {
            ARouter.getInstance().build("/documents/LocalActivity").navigation(this,100) }
        val manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.VERTICAL
        v.documentsRv.layoutManager = manager
        v.documentsRv.addItemDecoration(SignLineDecoration(this))
        documentsAdapter.setOnItemChildCLickListener{adapter,id,position->
            if(id== R.id.documents_delete_layout){
                //删除数据
                vm.delDocuments(documentsAdapter.data[position].fileId)
            }else{
                var str = documentsAdapter.data[position].filePath.substring(
                    documentsAdapter.data[position].filePath.lastIndexOf("."))
                when (str) {
                    ".pdf" -> {
                        val localPath = filePath+"/"+documentsAdapter.data[position].fileName
                        if (File(localPath).exists()){
                            val bund = Bundle()
                            bund.putString("path",localPath)
                            ARouter.getInstance().build("/documents/PDFActivity").with(bund).navigation()
                        }else{
                            vm.downloadFile(documentsAdapter.data[position].filePath,localPath)
                        }
                    }
                    ".txt" -> {
                        val localPath = filePath+"/"+documentsAdapter.data[position].fileName
                        if (File(localPath).exists()){
                            val bund = Bundle()
                            bund.putString("path",localPath)
                            ARouter.getInstance().build("/documents/PDFActivity").with(bund).navigation()
                        }else{
                            vm.downloadFile(documentsAdapter.data[position].filePath,localPath)
                        }
                    }
                    ".mp3" -> {
                        val bund = Bundle()
                        bund.putString("path",documentsAdapter.data[position].filePath)
                        ARouter.getInstance().build("/documents/MusicActivity").with(bund).navigation()
                    }
                    ".mp4" -> {
                        val bund = Bundle()
                        bund.putString("path",documentsAdapter.data[position].filePath)
                        ARouter.getInstance().build("/documents/VideoActivity").with(bund).navigation()
                    }
                    else -> {
                        val bund = Bundle()
                        bund.putString("path",documentsAdapter.data[position].filePath)
                        ARouter.getInstance().build("/documents/PhotoActivity").with(bund).navigation()
                    }
                }
            }
        }
        v.documentsRv.adapter = documentsAdapter
    }

    override fun initData() {
        vm.selDocuments(1)
    }

    override fun bindState() {
        lifecycleScope.launch {
            vm.mutableContainer.uiStateFlow.collect{
                if (it.loadState){
                    documentsAdapter.adds(it.data)
                }
                if (it.syncState){
                    vm.selDocuments(1)
                }
                if (it.documentsState){
                    documentsAdapter.setNewInstance(it.data)
                }
                if (it.delSate){
                    vm.selDocuments(1)
                }
                if (it.insertState){
                    vm.selDocuments(1)
                }
                if (it.downloadState){
                    val bund = Bundle()
                    bund.putString("path",it.path)
                    ARouter.getInstance().build("/documents/PDFActivity").with(bund).navigation()
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == 100){
            val bund = data!!.extras
            if (bund!=null){
                val name = bund.getString("name")
                val path = bund.getString("path")
                vm.insertDocuments(path!!,name!!,1)
            }
        }
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityDocumentsBinding.inflate(LayoutInflater.from(this))
    }
}